/******************************************************************************
 *
 * Copyright:
 *    (C) 2006 Embedded Artists AB
 *
 * File:
 *    pca9532.c
 *
 * Description:
 *    Implements hardware specific routines
 *
 *****************************************************************************/


#include "pca9532.h"

/*****************************************************************************
 *
 * Description:
 *    Initialize the io-pins and find out if HW is ver 1.0 or ver 1.1
 *
 ****************************************************************************/
tBool
pca9532Init(void)
{
  tU8 initCommand[] = {0x12, 0x97, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00};
  //                                                         04 = LCD_RST# low
  //                                                         10 = BT_RST# low

  //initialize PCA9532
  if (I2C_CODE_OK == pca9532(initCommand, sizeof(initCommand), NULL, 0))
    return TRUE;
  else
    return FALSE;
}


/*****************************************************************************
 *
 * Description:
 *  Sets state of PCA9532 pin
 * Params:
 *  [in] pinNum - number of pin to be set
 *  [in] value - value to be set
 *
 *
 ****************************************************************************/
void
setPca9532Pin(tU8 pinNum, tU8 value) {
  tU8 command[] = {0x00, 0x00};
  tU8 regValue;
  tU8 mask;
  
  if (pinNum < 4) // LED0 to LED3
    command[0] = 0x06;
  else if (pinNum < 8)// LED4 to LED7
    command[0] = 0x07;
  else if (pinNum < 12)// LED8 to LED11
    command[0] = 0x08;
  else
    command[0] = 0x09;// LED12 to LED15
    
  pca9532(command, 1, &regValue, 1);
  
  mask = (3 << 2*(pinNum % 4));
  
  regValue &= ~mask;
  
  if (value == 0)
    command[1] = 0x01;
  else
    command[1] = 0x00;
    
  command[1] <<= 2*(pinNum % 4);
  
  command[1] |= regValue;

  pca9532(command, sizeof(command), NULL, 0);
}

/*****************************************************************************
 *
 * Description:
 *  Sets value to all pins of PCA9532
 * Params:
 *  [in] value - value to be set
 *
 *
 ****************************************************************************/
void setAll(tU8 value) {
	int i =0;
	for ( i=0; i<16; i++){
		setPca9532Pin(i,value);
	}
}

/*****************************************************************************
 *
 * Description:
 *  Process entry function
 *  Sets pins of PCA9532 according to depth value
 * Params:
 *  [in] depth - value to be set
 *  [in] pca9532Present - true if PCA9532 is present
 *
 *
 ****************************************************************************/

void runLeds(int depth, tU8 pca9532Present) {

	if (TRUE == pca9532Present) {
		setAll(1);
		int i = 0;

		for (i = 0; i < depth; i++) {
			setPca9532Pin(i, 0);
		}

	} else {
		printf("pca9532 NOT Present \n");

	}
}

